
let layerIndex;
/**
 * 弹出学生对话框
 */
function showStudenDlg(id){

    let title ="新增学生"
    if (id){
        //是编辑
        title="编辑学生"
        $("#formId").css("display", "block");

        //读取学生信息,赋值
        $.ajax({
            url:"/api/student/"+id,
            method: "GET"
        }).done(result=>{

            console.log(result)

            //遍历result
            $.each(result, function (key, value){
                //修改
                var field = $('#studForm [name="' + key + '"]');

                if  (field.is(':radio')) {
                    field.filter('[value="' + value + '"]').prop(':checked', true);//xuan zhong
                } else if (field.is(':checkbox')) {
                    field.prop('checked', value === "yes");//
                } else {
                    field.val(value); //
                }
            });
        })


    }else {
        //是新增
        $("#studForm")[0].reset();
        $("#formId").css("display", "none");
    }

    layerIndex= layer.open({
        type:1,
        title:title,
        area:['520px', 'auto'],
        content:$("#studForm")//捕获层
    });


}

function getSearchCondtion() {

    let formData = {};
    // 遍历每个输入元素，将其值存储到 formData 对象中
    $('#queryForm').find('input, select').each(function () {
        let name = $(this).attr('name'); // 获取元素的 name 属性
        let value = $(this).val(); // 获取元素的值

        // 只有 name 属性存在且值不为空才会添加到 formData 中
        if (name && value) {
            formData[name] = value;
        }
    });


    return formData;
}



layui.use(function () {
    // （1）
    layui.form.on('submit(stud-dlg)', function (data) {
        event.preventDefault();
        commitStuDlg();
    });

    // （2）表格初始化
    const table = layui.table;
    let student = getSearchCondtion();

    // 创建渲染实例
    table.render({
        elem: '#tbStudent',
        url: '/api/student/getbypage',
        method: "POST",
        contentType: 'application/json',
        where: {"data": student},
        page: true,
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'id', fixed: 'left', width: 80, title: 'id', sort: true},
            {field: 'name', title: '姓名'},
            {
                field: 'sno',
                title: '学号',
                width: 150,
            },
            {
                field: 'sex', width: 80, title: '性别', sort: true,
                templet: d => d.sex === 1 ? '男' : (d.sex === 2 ? '女' : '未知'),
            },
            {field: 'age', width: 100, title: '年龄', sort: true},
            {fixed: 'right', title: '操作', width: 134, minWidth: 125, templet: '#editTemplate'}
        ]],
        done: function (rs) {
            // console.log(rs)
        }
    });

    // 触发单元格工具事件
    table.on('tool(tbStudent)', function (obj) {
        var data = obj.data;
        if (obj.event === 'edit') {
            showStudenDlg(data.id);
        }
    });
});

function showStudenDlg(id) {
    let title = "新增学生";
    if (id) {
        // 是编辑
        title = "编辑学生";
        $("#formId").css("display", "block");

        // 读取学生信息，赋值
        $.ajax({
            url: "/api/student/" + id,
            method: "GET"
        }).done(result => {
            console.log(result);

            // 遍历result
            $.each(result, function (key, value) {
                // 修改
                var field = $('#studForm [name="' + key + '"]');

                if (field.is(':radio')) {
                    field.filter('[value="' + value + '"]').prop('checked', true);
                } else if (field.is(':checkbox')) {
                    field.prop('checked', value === "yes");
                } else {
                    field.val(value);
                }
            });
        });
    } else {
        // 是新增
        $("#studForm")[0].reset();
        $("#formId").css("display", "none");
    }

    layerIndex = layer.open({
        type: 1,
        title: title,
        area: ['520px', 'auto'],
        content: $("#studForm")// 捕获层
    });
}

function commitStuDlg() {
    let id = $("#id").val();
    let formData = $("#studForm").serialize();
    if (id != null && id != "") {
        // 是更新学生
        $.ajax({
            url: "/api/student/update",
            method: "PUT",
            data: formData
        }).done(result => {
            console.log(result);
            if (result.code === 0) {
                // 关闭弹窗
                console.log("update success!");
                if (layerIndex) {
                    layer.close(layerIndex);
                }
                // 刷新页面
                location.reload();
            }
        }).fail((jqXHR, textStatus, errorThrown) => {
            console.error("Request failed: " + textStatus + " - " + errorThrown);
            alert("An error occurred, Please try again.");
        });
    } else {
        // 新增学生
        $.ajax({
            url: "/api/student/add",
            method: "POST",
            data: formData
        }).done(result => {
            console.log(result);
            if (result.id) {
                // 关闭弹窗
                console.log("add success!");
                if (layerIndex) {
                    layer.close(layerIndex);
                }
                // 刷新页面
                location.reload();
            }
        }).fail((jqXHR, textStatus, errorThrown) => {
            console.error("Request failed: " + textStatus + " - " + errorThrown);
            alert("An error occurred, Please try again.");
        });
    }

    $("#btnOK").prop("disabled", true).addClass("layui-btn-disabled");
}

function search() {
    let student = getSearchCondtion();

    const table = layui.table;
    table.reloadData('tbStudent', {
        where: {data:student},
    });
    console.log("where condition:"+JSON.stringify(student))
}


function deleteConfirm() {
    const table = layui.table;
    // 获取表格的选中状态
    const checkStatus = table.checkStatus('tbStudent');
    const data = checkStatus.data;

    if (data.length === 0) {
        // 如果没有选中任何记录，给出提示
        layer.msg('请选择要删除的学生信息', {icon: 2});
        return;
    }

    // 弹出确认对话框
    layer.confirm('你真的要删除吗？一旦删除，不可恢复', {icon: 3, title:'确认删除'}, function (index) {
        // 遍历选中的记录
        data.forEach(function (item) {
            // 发送删除请求
            $.ajax({
                url: "/api/student/delete/" + item.id,
                method: "DELETE"
            }).done(function (result) {
                console.log(result);
            }).fail(function (jqXHR, textStatus, errorThrown) {
                console.error("Request failed: " + textStatus + " - " + errorThrown);
                alert("An error occurred, Please try again.");
            });
        });

        // 关闭确认对话框
        layer.close(index);
        // 刷新页面
        location.reload();
    });
}




function commitStuDlg(){
    let id= $("#id").val()
    let formData = $("#studForm").serialize();
    if (id!=null && id!=""){
        //是更新学生
        $.ajax({
            url: "/api/student/update",
            method:"PUT",
            data:formData
        }).done(result=> {
            console.log(result);
            if (result.code === 0) {
                //（3）关闭弹窗
                console.log("add success!")
                if (layerIndex)
                    layer.close(layerIndex)
            }
            //刷新页面
            location.reload();


        }).fail((jqXHR, textStatus, errorThrown)=>{
            console.error("Request failed: " + textStatus + " - " + errorThrown);
            //
            alert("An error occurred, Please try again.");
        });


    }else {

//新增学生需要进行
        //（2）发送

        $.ajax({
            url: "/api/student/add",
            method:"POST",
            data:formData
        }).done(result=>{
            console.log(result);
            if (result.id){
                //（3）关闭弹窗
                console.log("add success!")
                if(layerIndex)
                    layer.close(layerIndex)

            }
            //刷新
            location.reload();

        }).fail((jqXHR, textStatus, errorThrown)=>{
            console.error("Request failed: " + textStatus + " - " + errorThrown);
            //
            alert("An error occurred, Please try again.");
        });

    }



    $("#btnOK").prop("disabled", true).addClass("layui-btn-disabled");//



}



function deleteById(id){

    //shanchu
    layer.confirm('你真的要删除吗？一旦删除，不可恢复', {icon: 3}, function(){


            $.ajax({
                url:"/api/student/delete/"+id,
                method:"DELETE"
            }).done(result=>{
                loadStudentList();

            })
        layer.closeAll();//guanbi



    }, function(){

    });
}